import React, { useEffect, useState } from 'react'
import { getCurrentCity } from '../../api/index'
import { Loading } from 'zarm'
import styles from './map.module.css'
import axios from '../../utils/request';
import HouseItem from "../../components/HouseItem/index";
import { set } from 'nprogress';
const BMap = window.BMap;
let map = null;
const labelStyle = {
    cursor: 'pointer',
    border: '1px solid rba(255,0,0)',
    padding: '0px',
    whiteSpace: 'nowrap',
    fontSize: '12px',
    color: 'rgb(255,255,255)',
    textAlign: 'center'
}
const Map = () => {
    //表示存储小区的房源;
    const [list, setList] = useState([]);
    //控制列表的显示和隐藏;
    const [loaded, setLoaded] = useState(false);
    const [cityid, setCityid] = useState('')
    useEffect(() => {
        initMap()
    }, [])
    //初始化
    const initMap = async () => {
        const { label, value } = await getCurrentCity();
        //实例化地图
        map = new BMap.Map('container')
        // map.centerAndZoom(new BMap.Point(116.404, 39.915), 12);
        map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
        // 创建地址解析器实例     
        let myGeo = new BMap.Geocoder();
        // 1:需要解析的详细的地址
        // 2:回调函数，回调函数的形参就是解析出来地址的坐标;
        // 3:城市的名字;
        myGeo.getPoint(label, async (point) => {
            if (point) {
                map.centerAndZoom(point, 11);
                //添加一个平移缩放的控件;
                map.addControl(new BMap.NavigationControl())
                //添加比例尺控件;
                map.addControl(new BMap.ScaleControl());
                //在地图上面去添加一些覆盖物;
                //传递过去城市独特的标识;
                renderOverlays(value);
            }
        },
            label);
        //实例化出来的地图，只要稍微移动一下，当前具体的房源列表--就消失掉;
        map.addEventListener('movestart', () => {
            setLoaded(false)
        })
    }
    const renderOverlays = async (id) => {
        //覆盖物是根据请求的多少条数据来进行创建
        Loading.show('加载中')
        const res = await axios.get("/area/map", {
            params: {
                id
            }
        })
        //请求完成了,把toast给关闭掉
        Loading.hide();
        //写一个方法---来描述缩放的级别--和覆盖物类型;
        const { type, nextLevel } = getTypeAndZoom();
        //得到类型和级别之后，就该创建覆盖物了;
        res.data.body.forEach(item => {
            //创建一个方法专门用来创建覆盖物;
            createOverlays(type, nextLevel, item);
        })
    }

    const getTypeAndZoom = () => {
        //计算一下覆盖物的类型和下一级的缩放级别;
        //区-----11
        //镇-----13
        //小区-----15
        //先用一个方法来获取当前地图的缩放级别
        const curZoom = map.getZoom();
        let type, nextLevel;
        if (curZoom >= 10 && curZoom < 12) {
            type = "circle";
            nextLevel = 13;
        } else if (curZoom >= 12 && curZoom < 14) {
            type = "circle";
            nextLevel = 15;
        } else if (curZoom >= 14 && curZoom < 16) {
            type = "rect"
        }

        return {
            type,
            nextLevel
        }
    }
    //创建覆盖物的方法;
    const createOverlays = (type, nextLevel, item) => {
        const {
            coord: {
                latitude,
                longitude
            },
            label,
            value,
            count
        } = item;
        setCityid(value)
        //创建中心点坐标;
        var point = new BMap.Point(longitude, latitude);
        if (type === 'rect') {
            //定义一个函数来创建覆盖物是小方块的
            createRect(point, label, count, value);
        } else {
            //搞一个圆的覆盖物;
            createCircle(point, label, count, value, nextLevel)
        }
    }

    //创建圆的方法；
    const createCircle = (point, areaName, count, id, level) => {
        const opts = {
            //坐标
            position: point,
            //偏移量
            offset: new BMap.Size(-35, -35)
        }
        /**
         * 1:表示的是覆盖物文字-可以直接在里面写文字;
         * ---通过setContent---方法;
         * ------就不会生效了,直接写成空字符串;
         * 2:表示覆盖物的配置对象
         */
        const label = new BMap.Label('', opts);
        // 创建文本内容;
        label.setContent(`
          <div class="${styles.bubble}">
          <p class="${styles.name}">${areaName}</p>
          <p>${count}套</p>
          </div>
        `)
        //设置一些样式;
        label.setStyle(labelStyle);
        label.addEventListener('click', e => {
            //获取覆盖物下级的数据
            renderOverlays(id);
            //方法地图;
            map.centerAndZoom(point, level);
            //清除副高五;
            setTimeout(() => {
                map.clearOverlays()
            }, 0);
        })
        //把写好的覆盖物给添加到地图中;
        map.addOverlay(label);
    }

    //创建小方块覆盖物的方法
    const createRect = (point, areaName, count, value) => {
        const opts = {
            position: point,
            offset: new BMap.Size(-50, -28)
        }
        const label = new BMap.Label('', opts);
        label.setContent(`
          <div class="${styles.rect}">
           <span class="${styles.housename}">${areaName}</span>
           <span class="${styles.housenum}">${count}套</span>
          </div>
        `)
        //设置样式
        label.setStyle(labelStyle)
        //点击事件;
        label.addEventListener("click", e => {
            //小区点击之后---被点击的 小区会唯一到中心点附近;
            //在移动端如何获取---手指点击的位置;
            const { clientX, clientY } = e.changedTouches[0];
            //点击哪个就把中心位置让给哪个
            //让地图移动;
            const x = (window.innerWidth) / 2 - clientX;
            const y = (window.innerHeight) / 2 - clientY;
            //让地图位移;
            map.panBy(x, y);
            //获取这个小区下面的房源数据;
            getCommitHouse(value);
        })

        map.addOverlay(label)
    }

    const getCommitHouse = async (id) => {
        Loading.show('加载嗷嗷嗷...');
        //获取小区下面的房源列表;
        const res = await axios.get("/houses", {
            params: {
                cityId: id
            }
        })
        Loading.hide();
        setList(res.data.body.list);
        setLoaded(true)
    }

    const renderHouseList = () => {
        return list.map(item => (
            <HouseItem key={item.houseCode} {...item} cityId ={cityid}></HouseItem>
        ))
    }
    return <div>
        <div id="container" style={{ width: '100%', height: '460px' }}></div>
        <div className={[styles.houseList, loaded ? styles.show : ''].join(' ')}>
            <div className={styles.titleWrap}>
                <h3 className={styles.listTitle}>房源列表</h3>
                <a className={styles.titleMore} href="/buyhouse">更多房源</a>
            </div>
            <div className={styles.houseItems}>
                {renderHouseList()}
            </div>
        </div>
    </div>
}
export default Map